package com.yupi.yupicturebackend.api.imageSearch.sub;

import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class GetImageFirstUrlApi {
    public static void main(String[] args) {
        String url = "https://graph.baidu.com/s?card_key=&entrance=GENERAL&extUiData[isLogoShow]=1&f=all&isLogoShow=1&session_id=1462102440230947431&sign=121c3e97cd54acd88139901749360154&tpl_from=pc";
        String imageUrl = getImageFirstUrl(url);
        System.out.println(imageUrl);
    }

    public static String getImageFirstUrl(String url) {
        try {
            // 使用Jsoup获取HTML内容
            Document document = Jsoup.connect(url).timeout(5000).get();
            // 获取所有 script标签
            Elements scriptElements = document.getElementsByTag("script");
            for (Element scriptElement : scriptElements) {
                String scriptContent = scriptElement.html();
                if (scriptContent.contains("\"firstUrl\"")) {
                    Pattern pattern = Pattern.compile("\"firstUrl\"\\s*:\\s*\"(.*?)\"");
                    Matcher matcher = pattern.matcher(scriptContent);
                    if (matcher.find()) {
                        String firstUrl = matcher.group(1);
                        // 处理转义字符
                        firstUrl = firstUrl.replace("\\/", "/");
                        return firstUrl;
                    }
                }
            }
            throw new BusinessException(ErrorCode.OPERATION_ERROR,  "获取图片链接失败");
        } catch (Exception e) {
            log.error("获取图片链接失败：" + e.getMessage());
            throw new BusinessException(ErrorCode.OPERATION_ERROR,  "获取图片链接失败");
        }
    }
}
